package main

import (
	"fmt"
	"gitee.com/worklz/dtm-tcc-demo/common/util"
	"gitee.com/worklz/dtm-tcc-demo/server-inventory/domain/middleware"
	"gitee.com/worklz/dtm-tcc-demo/server-inventory/handler"
	_ "gitee.com/worklz/dtm-tcc-demo/server-inventory/pkg/boot"
	"gitee.com/worklz/dtm-tcc-demo/server-inventory/pkg/global"
	"gitee.com/worklz/dtm-tcc-demo/server-inventory/pkg/shutdown"
	inventorypb "gitee.com/worklz/dtm-tcc-demo/server-inventory/proto/inventory"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"
	"net"
)

func main() {
	// 关闭处理（释放资源等）
	defer shutdown.Handle()

	// 监听端口
	lis, err := net.Listen("tcp", global.Config.Server.Addr)
	if err != nil {
		panic(fmt.Sprintf("无法监听端口: %v", err))
	}

	// 获取有效的本机IP
	localIP := util.GetValidLocalIP()
	// 解析实际监听的地址信息
	addr := lis.Addr().String()
	_, port, err := net.SplitHostPort(addr)
	if err != nil {
		// 解析失败时直接输出完整地址
		fmt.Printf("gRPC %s 启动成功，监听地址: %s\r\n", global.Config.Server.Desc, addr)
	} else {
		// 显示本机IP和监听端口
		fmt.Printf("gRPC %s 启动成功，监听地址: %s:%s\r\n", global.Config.Server.Desc, localIP, port)
	}

	// 创建gRPC服务器，并添加日志拦截器
	s := grpc.NewServer(
		grpc.UnaryInterceptor(middleware.LogInterceptor),
	)

	// 注册订单服务
	inventorypb.RegisterInventoryServiceServer(s, handler.NewInventoryHandler())

	// 注册健康检查服务
	healthpb.RegisterHealthServer(s, health.NewServer())

	// 启动服务
	if err := s.Serve(lis); err != nil {
		panic(fmt.Sprintf("服务启动失败: %v", err))
	}
}
